﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using Distribution.General;
using Distribution.Service;
using DistributionApplication.Controls.Events;
using Entities;

namespace DistributionApplication
{
    public partial class frmHome : frmBase
    {
        #region - Private Attributes -

        private FrmAbout m_FrmAbout;
        private frmDistributionEditor m_FrmDistribution;
        private Form m_FrmSettings;

        #endregion

        #region - Properties -

        public FrmAbout FrmAbout
        {
            get
            {
                if (m_FrmAbout == null)
                    m_FrmAbout = new FrmAbout();

                return m_FrmAbout;
            }
        }

        public frmDistributionEditor FrmDistributionEditor
        {
            get
            {
                if (m_FrmDistribution == null)
                    m_FrmDistribution = new frmDistributionEditor();

                return m_FrmDistribution;
            }
        }

        public Form FrmSettings
        {
            get
            {
                if (m_FrmSettings == null) 
                {
                    if (Settings.DistributionApplicationMode == DistributionApplicationMode.GPS)
                        m_FrmSettings = new frmGPSSettings();
                    else
                        m_FrmSettings = new frmInspectionSettings();
                }

                return m_FrmSettings;
            }
        }

        #endregion

        #region - Constants -

        private readonly string HomeTitle = "Pole Position Mobile | Home";

        #endregion

        #region - Constructor -

        public frmHome()
        {
            InitializeComponent();
        }

        #endregion

        #region - Event handlers -

        private void frmHome_Load(object sender, EventArgs e)
        {
            Title = HomeTitle;

            LButtonText = "New";
            RButtonText = "Menu";
            SetLContextMenu(contextMenuDistribution);
            LButtonMenuXOffset = 1;
            LButtonMenuYOffset = 40;
            SetRContextMenu(contextMenuGeneral);
            RButtonMenuXOffset = 4;
            RButtonMenuYOffset = 60;

            grdDistribution.ConfigureGrid();
        }

        private void contextMenuInspections_Popup(object sender, EventArgs e)
        {
            mitDuplicateLast.Enabled = (grdDistribution.GetLastInspection() != null);
        }

        #endregion

        #region - Menu item event handlers -

        private void mitAbout_Click(object sender, EventArgs e)
        {
            FrmAbout.ShowDialog();
        }

        private void mitExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void mitCreateBackup_Click(object sender, EventArgs e)
        {
            Hide();
            SaveFileDialog saveFile = new SaveFileDialog();
            Application.DoEvents();

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                Show();
                pnlBackup.Visible = true;
                DirectoryInfo _DestinationDirectory = new DirectoryInfo(saveFile.FileName);

                Application.DoEvents();
                string[] _AppDataFolderFiles = Directory.GetFiles(PPIConstants.K_AppDataFolder);
                string[] _ImagesFolderFiles = Directory.GetFiles(PPIConstants.K_ImagesFolder);
                prgBackup.Maximum = _AppDataFolderFiles.Length + _ImagesFolderFiles.Length;
                prgBackup.Minimum = 0;
                prgBackup.Value = 0;
                lblBackup.Text = "Proccessing...\r\n" + prgBackup.Value + " of " + prgBackup.Maximum;
                pnlBackup.Visible = true;
                pnlBackup.BringToFront();
                Application.DoEvents();
                
                if (!Directory.Exists(_DestinationDirectory.FullName + Path.DirectorySeparatorChar + PPIConstants.K_BackupFolder))
                    Directory.CreateDirectory(_DestinationDirectory.FullName + Path.DirectorySeparatorChar + PPIConstants.K_BackupFolder);

                string _Destination = _DestinationDirectory.FullName + Path.DirectorySeparatorChar + PPIConstants.K_BackupFolder + Path.DirectorySeparatorChar + DateTime.Now.ToString("yyyyMMddHHmmss") + "\\";
                
                if (!Directory.Exists(_Destination + "Images\\"))
                    Directory.CreateDirectory(_Destination + "Images\\");
            
                foreach (string _Element in _AppDataFolderFiles)
                {
                    File.Copy(_Element, _Destination + Path.GetFileName(_Element), true);
                    prgBackup.Value++;
                    lblBackup.Text = "Proccessing...\r\n" + prgBackup.Value + " of " + prgBackup.Maximum ;
                    Application.DoEvents();
                }

                foreach (string _Element in _ImagesFolderFiles)
                {
                    File.Copy(_Element, _Destination + "Images\\" + Path.GetFileName(_Element), true);
                    prgBackup.Value++;
                    lblBackup.Text = "Proccessing...\r\n" + prgBackup.Value + " of " + prgBackup.Maximum ;
                    Application.DoEvents();
                }

                pnlBackup.Visible = false;
                Application.DoEvents();
                
                if (MessageBox.Show("Backup done." + Environment.NewLine + "Clear database?", PPIConstants.K_AppName, MessageBoxButtons.YesNo, MessageBoxIcon.None, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                {
                    Application.DoEvents();
                    if (Directory.Exists(PPIConstants.K_ImagesFolder))
                        Directory.Delete(PPIConstants.K_ImagesFolder, true);
                    Directory.CreateDirectory(PPIConstants.K_ImagesFolder);

                    LDistribution.ClearDataBase();
                    Application.DoEvents();
                    grdDistribution.ConfigureGrid();
                    
                }
            }
            else
                Show();

            SetCorrectOrder();
        }

        private void mitSettings_Click(object sender, EventArgs e)
        {
            Hide();
            FrmSettings.ShowDialog();
            Show();
        }

        private void mitNew_Click(object sender, EventArgs e)
        {
            if (!m_GPS.HasSolution)
            {
                DialogResult _result = MessageBox.Show("There is no solution available.\n Do you still want to continue?", "PPI Location", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                
                if (_result == DialogResult.No)
                    return;
            }

            FrmDistributionEditor.PoleToBeLoaded = null;
            FrmDistributionEditor.Mode = EditorMode.New;
            FrmDistributionEditor.ResetControls();
            Hide();
            FrmDistributionEditor.ShowDialog();
            Show();
            
            grdDistribution.ReloadGrid();
        }

        private void mitDuplicateLast_Click(object sender, EventArgs e)
        {
            if (!m_GPS.HasSolution)
            {
                DialogResult _result = MessageBox.Show("There is no solution available.\n Do you still want to continue?", "PPI Location", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

                if (_result == DialogResult.No)
                    return;
            }

            EPole selectedPole = grdDistribution.GetLastInspection();

            FrmDistributionEditor.Mode = EditorMode.Duplicate;
            FrmDistributionEditor.PoleToBeLoaded = selectedPole;

            Hide();
            FrmDistributionEditor.ShowDialog();
            Show();

            grdDistribution.ReloadGrid();            
        }

        private void grdDistributions_ClickedDelete(object sender, GridEventArgs e)
        {
            DialogResult _result = MessageBox.Show("Do you confirm you want to delete this asset?", "PPI Distribution", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

            if (_result == DialogResult.No)
                return;

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                EPole selectedPole = new EPole();
                selectedPole.Id = e.Id;
                
                LPole.Delete(selectedPole);
                
                grdDistribution.ReloadGrid();
            }
            finally 
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void grdDistributions_ClickedDuplicate (object sender, GridEventArgs e)
        {
            if (!m_GPS.HasSolution)
            {
                DialogResult _result = MessageBox.Show("There is no solution available.\n Do you still want to continue?", "PPI Location", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
                if (_result == DialogResult.No)
                    return;
            }

            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            FrmDistributionEditor.Mode = EditorMode.Duplicate;
            FrmDistributionEditor.PoleToBeLoaded = selectedPole;

            Hide();
            FrmDistributionEditor.ShowDialog();
            Show();

            grdDistribution.ReloadGrid();   
        }

        private void grdDistributions_ClickedEdit(object sender, GridEventArgs e)
        {
            if (!m_GPS.HasSolution)
            {
                DialogResult _result = MessageBox.Show("There is no solution available.\n Do you still want to continue?", "PPI Location", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);

                if (_result == DialogResult.No)
                    return;
            }

            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            FrmDistributionEditor.Mode = EditorMode.Update;
            FrmDistributionEditor.PoleToBeLoaded = selectedPole;

            Hide();
            FrmDistributionEditor.ShowDialog();
            Show();

            grdDistribution.ReloadGrid();            
        }

        private void grdDistributions_ClickedAddMeter(object sender, GridEventArgs e)
        {
            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            List<EMeter> metersPerPole = LMeter.GetAll(selectedPole);
            if (metersPerPole.Count >= Settings.MaxMeterPerPole)
            {
                MessageBox.Show("You have reached the max amount of meters (" + Settings.MaxMeterPerPole + ") per poles.", "Message", MessageBoxButtons.OK, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button1);
                return;
            }

            selectedPole = LPole.GetBasicDataById(selectedPole);

            frmMeter meterForm = new frmMeter();
            meterForm.Pole = selectedPole;

            Hide();
            meterForm.ShowDialog();
            Show();

            grdDistribution.ReloadGrid();
        }

        private void grdDistributions_Meters(object sender, GridEventArgs e)
        {
            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            frmMeterHome frm = new frmMeterHome(LPole.GetBasicDataById(selectedPole));
            Hide();
            
            frm.ShowDialog();
            
            Show();
            grdDistribution.ReloadGrid();
        }

        #endregion

        private void grdDistribution_ClickedAddTransformer(object sender, GridEventArgs e)
        {
            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            selectedPole = LPole.GetBasicDataById(selectedPole);

            frmTransformer transformerForm = new frmTransformer();
            transformerForm.Pole = selectedPole;

            Hide();
            transformerForm.ShowDialog();
            Show();

            grdDistribution.ReloadGrid();
        }

        private void grdDistribution_ClickedTransformers(object sender, GridEventArgs e)
        {
            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            frmTransformerHome frm = new frmTransformerHome(LPole.GetBasicDataById(selectedPole));
            Hide();

            frm.ShowDialog();

            Show();
            grdDistribution.ReloadGrid();
        }

        private void grdDistribution_ClickedAddRecloser(object sender, GridEventArgs e)
        {
            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            selectedPole = LPole.GetBasicDataById(selectedPole);

            frmRecloser recloserForm = new frmRecloser();
            recloserForm.Pole = selectedPole;

            Hide();
            recloserForm.ShowDialog();
            Show();

            grdDistribution.ReloadGrid();
        }

        private void grdDistribution_ClickedAddSectionalizer(object sender, GridEventArgs e)
        {
            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            selectedPole = LPole.GetBasicDataById(selectedPole);

            frmSectionalizer sectinalizerForm = new frmSectionalizer();
            sectinalizerForm.Pole = selectedPole;

            Hide();
            sectinalizerForm.ShowDialog();
            Show();

            grdDistribution.ReloadGrid();
        }

        private void grdDistribution_ClickedReclosers(object sender, GridEventArgs e)
        {
            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            frmRecloserHome frm = new frmRecloserHome(LPole.GetBasicDataById(selectedPole));
            Hide();

            frm.ShowDialog();

            Show();
            grdDistribution.ReloadGrid();
        }

        private void grdDistribution_ClickedSectionalizers(object sender, GridEventArgs e)
        {
            EPole selectedPole = new EPole();
            selectedPole.Id = e.Id;

            frmSectionalizerHome frm = new frmSectionalizerHome(LPole.GetBasicDataById(selectedPole));
            Hide();

            frm.ShowDialog();

            Show();
            grdDistribution.ReloadGrid();
        }
    }
}